﻿using Mongodb;
using ProductTool.Dao;
using ProductTool.Entity;
using ProductTool.Tools;
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Threading;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Diagnostics;
using Newtonsoft.Json;
using MassTransit.Util;

namespace ProductTool.Service
{
    public class ItemServiceProp
    {
        ItemDao dao = new ItemDao();
        BrandDao bDao = new BrandDao();
        List<BrandEntity> brandList = new List<BrandEntity>();
        List<Property> propList = new List<Property>();
        List<PropertyValue> propValueList = new List<PropertyValue>();
        public ItemServiceProp() {
            brandList = bDao.QueryBrand();
      
        }
        public void Process() {

            propList = dao.QueryCategoryProp();
            var list = new List<JDItem>();
            int page = 1;
            string maxGoodsSN = string.Empty;//dao.QueryMaxGoodsSNByProp();
            if (string.IsNullOrEmpty(maxGoodsSN))
            {
                maxGoodsSN = "";
            }
            List<Task> thList = new List<Task>();
            propValueList = dao.QueryPropValue();
            do
            {
                try
                {
                    thList.Clear();
                    Stopwatch sw = new Stopwatch();
                    sw.Start();
                    list = dao.QueryJdItem(page, 100, maxGoodsSN);
                    if (list.Count == 0)
                    {
                        break;
                    }
                    var tk = new TaskFactory(new LimitedConcurrencyLevelTaskScheduler(10));
                    var imList = dao.CheckJDInIM(list.Select(p => p.sku).ToList());                
                    if (imList.Count==0)
                    {
                        foreach (var item in list)
                        {
                            dao.UpdateJDItemPropDetail(item.sku);
                            Console.WriteLine($"{item.sku}不存在im中");
                        }
                    }
                    foreach (var item in imList)
                    {
                        thList.Add(tk.StartNew(() =>
                        {
                            var jd = list.FirstOrDefault(p => p.sku == item.goods_sn);
                            if (jd != null)
                            {
                                createItemProp(jd, item.item_number);
                            }
                        }));
                    }
                    Task.WaitAll(thList.ToArray());
                    sw.Stop();
                    Console.WriteLine($".................page {page} complete.........{sw.Elapsed.Milliseconds}");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            } while (true);
           
            Console.WriteLine("-----------------------all done----------------------------------");
            Console.ReadKey();
        }
        private void createItemProp(JDItem item,string item_number)
        {      
        
                var props = GetPropertyInfo(item);
                List<ItemPropValue> itemPropList = new List<ItemPropValue>();
                foreach (var p in props)
                {
                    //检测属性名是否存在
                    var prop = propList.FirstOrDefault(o => o.property_name==p.Key && o.category_id==item.c3_id);
                    if (prop!=null)
                    {
                        ////检测属性值是否存在
                        //var pValue = propValueList.FirstOrDefault(pv=>pv.property_id==prop.property_id && pv.property_value==p.Value);
                        ////var pValue = dao.QueryPropValue(new PropertyValue {
                        ////  property_id=prop.property_id,
                        ////  property_value=p.Value
                        ////});                    
                        //if (pValue==null)
                        //{
                        //    pValue = new PropertyValue { 
                        //     property_id=prop.property_id,
                        //     property_value=p.Value
                        //    };
                        //    //创建新属性值
                        //    var id=dao.CreatePropValue(pValue);
                        //    pValue.property_value_id = id;
                        //    propValueList.Add(pValue);
                        //}
                        //关联商品属性
                        itemPropList.Add(new ItemPropValue
                        {
                            item_number = item_number,
                            property_id = prop.property_id,
                            user_input = p.Value,
                            user_input_eng = p.Value
                        });                        
                    }                
                }
                if (itemPropList.Count>0)
                {
                  dao.CreateItemPropValue(itemPropList);
                }
              
               var detailInfo = BuildPropDetail(props);
                //更新商品属性信息字段
                dao.UpdateItemPropDetail(item_number, detailInfo);
                dao.UpdateJDItemPropDetail(item.sku);
                Console.WriteLine($"{item.sku} succes");
                      
        }
        private string BuildPropDetail(Dictionary<string, string> data)
        {       
            return JsonConvert.SerializeObject(data);
        }
     
        private Dictionary<string,string> GetPropertyInfo(JDItem book)
        {
            Dictionary<string, string> result = new Dictionary<string, string>();       
          
            if (!string.IsNullOrEmpty(book.publishers))
            {              
                result.Add("出版社", book.publishers);               
            }
            if (!string.IsNullOrEmpty(book.isbn))
            {
                result.Add("ISBN", book.isbn);              
            }
            if (!string.IsNullOrEmpty(book.book_package))
            {
                result.Add("包装", book.book_package);              
            }
            if (!string.IsNullOrEmpty(book.publish_time))
            {
                result.Add("出版时间", book.publish_time);
            }
            if (!string.IsNullOrEmpty(book.pages))
            {
                result.Add("页码", book.pages);              
            }
            if (!string.IsNullOrEmpty(book.papers))
            {
                result.Add("用纸", book.papers);              
            }
            if (!string.IsNullOrEmpty(book.author))
            {
                string author = book.author;
                if (!string.IsNullOrEmpty(book.editer))
                {
                    author += "," + book.editer;
                }
                if (!string.IsNullOrEmpty(book.transfer))
                {
                    author += "," + book.transfer;
                }
                if (!string.IsNullOrEmpty(book.drawer))
                {
                    author += "," + book.drawer;
                }
                result.Add("编者", author);              
            }           
            if (!string.IsNullOrEmpty(book.language))
            {
                result.Add("语言", book.language);                
            }
            if (book.print_no>0)
            {
                result.Add("版次", book.print_no.ToString());                
            }
            if (!string.IsNullOrEmpty(book.print_time))
            {
                result.Add("印刷时间", book.print_time);               
            }
            return result;
        }
    }
}
